package jlfm.lastfm.tools.mb;

import java.util.Iterator;

import jlfm.lastfm.tools.id3.ID3MetadataAdapter;

import org.musicbrainz.model.Artist;
import org.musicbrainz.model.Release;
import org.musicbrainz.model.Track;
import org.musicbrainz.wsxml.element.DiscList;

class MusicBrainzMetadataWrapper extends ID3MetadataAdapter {

	private Track track;

	private Release albumDetails;

	private Release albumOfTrack;

	private Artist artist;

	public MusicBrainzMetadataWrapper(Track track, Release album, Artist artist) {
		this.track = track;
		this.albumDetails = album;
		this.albumOfTrack = getAlbumOfTrack(track, album);
		this.artist = artist;
	}

	private Release getAlbumOfTrack(Track t, Release r) {
		if (t != null && r != null) {
			Iterator<Release> it = t.getReleases().iterator();
			while (it.hasNext()) {
				Release result = it.next();
				if (result.getId().equals(r.getId())) {
					return result;
				}
			}
		}
		return null;
	}

	public String getAlbumTitle() {
		if (albumDetails != null) {
			return albumDetails.getTitle();
		}
		return super.getAlbumTitle();
	}

	@Override
	public int getDiscNumber() {
		// TODO Test
		if (albumOfTrack != null && albumOfTrack.getDiscList() != null) {
			DiscList discList = albumOfTrack.getDiscList();
			return (int) (1 + discList.getOffset());
		}
		return super.getDiscNumber();
	}

	public String getArtistName() {
		if (artist != null) {
			return artist.getName();
		}
		return super.getArtistName();
	}

	public String getTrackTitle() {
		if (track != null) {
			return track.getTitle();
		}
		return super.getTrackTitle();
	}

	public int getYearOfRelease() {
		if (albumDetails != null
				&& albumDetails.getEarliestReleaseEvent() != null) {
			String date = albumDetails.getEarliestReleaseDate();
			if (date != null) {
				if (date.indexOf("-") != -1) {
					date = date.substring(0, 4);
				}
				return new Integer(date).intValue();
			}
		}
		return super.getYearOfRelease();
	}

	@Override
	public int getTrackNumber() {
		if (albumOfTrack != null) {
			return (int) (1 + albumOfTrack.getTrackList().getOffset());
		}
		return super.getTrackNumber();
	}

}
